package com.ccl.iot.views;


import android.app.ProgressDialog;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ccl.iot.R;
import com.ccl.iot.asynctask.SaveAllIrTask;
import com.ccl.iot.asynctask.SaveIrTask;
import com.ccl.iot.bean.CodeviewBean;
import com.ccl.iot.device.IOTBLir;
import com.ccl.iot.device.IOTSubBLir;
import com.ccl.iot.dialogs.AddSubBLirDialog;
import com.ccl.iot.dialogs.ModifyIconDialog;
import com.ccl.iot.ir.BlirConst;
import com.ccl.iot.ir.DBUtils;
import com.ccl.iot.publics.Messager;
import com.ccl.iot.publics.ThreadPoolUtils;
import com.ccl.iot.publics.UIUtils;
import com.hzy.tvmao.KookongSDK;
import com.hzy.tvmao.interf.IRequestResult;
import com.hzy.tvmao.ir.Device;
import com.kookong.app.data.AppConst;
import com.kookong.app.data.IrData;
import com.kookong.app.data.IrDataList;

import java.util.List;
import java.util.Set;

public class TestIrView extends LinearLayout {

    private SubBlirControlView mControlView;
    private ImageView mIvPrev;
    private ImageView mIvNext;
    private Button mBtnOk;
    private List<Integer> mRemoteids;
    private int mType;
    private int mIndex;
    private String mTextOk;
    private String mDevName;

    private IOTSubBLir mSubBLir;

    public ModifyIconDialog.OnSelectChangeListener mOnSelectChangeListener;
    private ProgressDialog mProgressDialog;
    private AddSubBLirDialog.OnApplianceSelectListener mOnApplianceSelectListener;

    private IrData mIrData;
    private int mCodeType;

    public TestIrView(Context context) {
        this(context, null);
    }

    public TestIrView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TestIrView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
        initListener();
    }

    private void initView() {
        View.inflate(getContext(), R.layout.view_test_ir, this);
        mControlView = (SubBlirControlView) findViewById(R.id.sbir_control_view);
        mIvPrev = (ImageView) findViewById(R.id.iv_test_ir_prev);
        mIvNext = (ImageView) findViewById(R.id.iv_test_ir_next);
        mBtnOk = (Button) findViewById(R.id.btn_test_ir_ok);

        mTextOk = mBtnOk.getText().toString().trim();
    }

    private void initListener() {
        mIvPrev.setOnClickListener(mOnClickListener);
        mIvNext.setOnClickListener(mOnClickListener);
        mBtnOk.setOnClickListener(mOnClickListener);
    }

    public void setData(int type, List<Integer> remoteids, ModifyIconDialog.OnSelectChangeListener onSelectChangeListener, String devname, AddSubBLirDialog.OnApplianceSelectListener listener) {
        mOnApplianceSelectListener = listener;
        mDevName = devname;
        mOnSelectChangeListener = onSelectChangeListener;
        mType = type;
        mRemoteids = remoteids;
        if (mRemoteids != null && mRemoteids.size() > 0) {
            mBtnOk.setText(mTextOk + "(" + (mIndex + 1) + "/" + mRemoteids.size() + ")");
            getTestIrCode();
        }
    }

    private View.OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.iv_test_ir_prev:
                    if (mRemoteids != null && mRemoteids.size() > 0 && mIndex > 0) {
                        mIndex--;
                        mBtnOk.setText(mTextOk + "(" + (mIndex + 1) + "/" + mRemoteids.size() + ")");
                        getTestIrCode();
                    }
                    break;
                case R.id.iv_test_ir_next:
                    if (mRemoteids != null && mRemoteids.size() > 0 && mIndex < mRemoteids.size() - 1) {
                        mIndex++;
                        mBtnOk.setText(mTextOk + "(" + (mIndex + 1) + "/" + mRemoteids.size() + ")");
                        getTestIrCode();
                    }
                    break;
                case R.id.btn_test_ir_ok:
                    if (mOnSelectChangeListener != null) {
                        mOnSelectChangeListener.onSelectChange();
                    }
                    createSubIrDev();
                    break;
            }
        }
    };

    private Runnable mUpdateControlTask = new Runnable() {
        @Override
        public void run() {
            mProgressDialog.cancel();
            mControlView.setIrSubDev(mSubBLir, false);
        }
    };

    private void getTestIrCode() {
        mProgressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
        mProgressDialog.show();
        if (mType == Device.AC) {
            KookongSDK.testIRDataById(mRemoteids.get(mIndex) + "", Device.AC, new IRequestResult<IrDataList>() {

                @Override
                public void onSuccess(String msg, IrDataList result) {
                    mProgressDialog.cancel();
                    String devType = BlirConst.getDevType(mType);
                    if (mSubBLir == null) {
                        IOTBLir blirDev = null;
                        if (mOnApplianceSelectListener != null) {
                            blirDev = mOnApplianceSelectListener.getBlirDev();
                        }
                        mSubBLir = new IOTSubBLir(devType, null, blirDev);
                    } else {
                        mSubBLir.getIRCode().clear();
                    }
                    List<IrData> irDatas = result.getIrDataList();
                    mIrData = irDatas.get(0);
                    mCodeType = mIrData.type;
                    Log.e("codeType", "codeType: " + mCodeType);
                    if (mCodeType == 1) {

                    } else {
                        //long devID, int subDevID,  String devType, int rid, HashMap<Integer, String> exts, String codeType, String aCode, long codeID
                        mSubBLir.setIRCode(new CodeviewBean(0, 0, devType, mIrData, DBUtils.CODE_TYPE_API, 0));
                        UIUtils.postTaskSafely(mUpdateControlTask);
                    }

                }

                @Override
                public void onFail(Integer errorCode, String msg) {
                    mProgressDialog.cancel();
                    //按红外设备授权的客户，才会用到这两个值
                    if (errorCode == AppConst.CUSTOMER_DEVICE_REMOTE_NUM_LIMIT) {//同一个设备下载遥控器超过了50套限制
                        ThreadPoolUtils.getInstance().addTask(new Runnable() {
                            @Override
                            public void run() {
                                long kkInitId = DBUtils.getKKInitId(mRemoteids.get(mIndex));
                                if (kkInitId >= 0) {
                                    boolean result = KookongSDK.init(getContext(), SubBlirControlView.KK_APP_KEY, kkInitId + "");
                                    Log.e("KKR", "Verify result is " + result + ", KK_irDeviceId: " + kkInitId);
                                    if (result) {
                                        SubBlirControlView.KK_irDeviceId = kkInitId;
                                        getTestIrCode();
                                    }
                                }
                            }
                        });
                        msg = "下载的遥控器超过了套数限制";
                    } else if (errorCode == AppConst.CUSTOMER_DEVICE_NUM_LIMIT) {//设备总数超过了授权的额度
                        msg = "设备总数超过了授权的额度";
                        Messager.Show(msg, Toast.LENGTH_SHORT);
                    }
                    Log.e("testIRDataById", "msg: " + msg + ", errorCode: " + errorCode);
                }

            });
        } else {
            //获取的是某套红外码部分按键，仅限按红外设备授权的客户（初始化时需要传递的deviceId），如果初始化时没有传deviceId，请求接口时会提示参数错误
            //对码流程获取rid = 4162 的 红外码, 批量获取红外码的方式是逗号隔开
            KookongSDK.testIRDataById(mRemoteids.get(mIndex) + "", mType, new IRequestResult<IrDataList>() {

                @Override
                public void onSuccess(String msg, IrDataList result) {
                    mProgressDialog.cancel();
                    String devType = BlirConst.getDevType(mType);
                    if (mSubBLir == null) {
                        IOTBLir blirDev = null;
                        if (mOnApplianceSelectListener != null) {
                            blirDev = mOnApplianceSelectListener.getBlirDev();
                        }
                        mSubBLir = new IOTSubBLir(devType, null, blirDev);
                    } else {
                        mSubBLir.getIRCode().clear();
                    }

                    List<IrData> irDatas = result.getIrDataList();
                    for (int i = 0; i < irDatas.size(); i++) {
                        Log.e("testIRDataById", "The rid is " + irDatas.get(i).rid);
                        IrData irData = irDatas.get(i);
                        Set<Integer> keySet = irData.exts.keySet();
                        for (Integer integer : keySet) {
                            String string = irData.exts.get(integer);
                            Log.e("testIRDataById", "irData.exts key: " + integer + ", value: " + string);
                        }
                        int size = irData.keys.size();
                        for (int j = 0; j < size; j++) {
                            IrData.IrKey irKey = irData.keys.get(j);
                            Log.e("testIRDataById", "irKey.fkey: " + irKey.fkey);
                            Log.e("testIRDataById", "irKey.pulse: " + irKey.pulse);
                            Log.e("testIRDataById", "irKey.fname: " + irKey.fname);
                            Log.e("testIRDataById", "--------------------------------------------------");

                            //long devID, int subDevID, String devType, String keyType, String keyName, String codeType, String aCode, long codeID
                            mSubBLir.setIRCode(new CodeviewBean(0, 0, devType, irKey.fkey, irKey.fname, DBUtils.CODE_TYPE_FIXED, BlirConst.kk2bl(irKey.pulse), 0));
                        }
                    }

                    UIUtils.postTaskSafely(mUpdateControlTask);
                }

                @Override
                public void onFail(Integer errorCode, String msg) {
                    mProgressDialog.cancel();
                    //按红外设备授权的客户，才会用到这个指
                    if (errorCode == AppConst.CUSTOMER_DEVICE_NUM_LIMIT) {//设备总数超过了授权的额度
                        msg = "设备总数超过了授权的额度";
                    }
                    //                TipsUtil.toast(TestIrCodeActivity.this, msg);
                    Log.e("testIRDataById", "msg: " + msg + ", errorCode: " + errorCode);
                    if (errorCode == AppConst.CUSTOMER_DEVICE_REMOTE_NUM_LIMIT) {
                        ThreadPoolUtils.getInstance().addTask(new Runnable() {
                            @Override
                            public void run() {
                                long kkInitId = DBUtils.getKKInitId(mRemoteids.get(mIndex));
                                if (kkInitId >= 0) {
                                    boolean result = KookongSDK.init(getContext(), SubBlirControlView.KK_APP_KEY, kkInitId + "");
                                    Log.e("KKR", "Verify result is " + result + ", KK_irDeviceId: " + kkInitId);
                                    if (result) {
                                        SubBlirControlView.KK_irDeviceId = kkInitId;
                                        getTestIrCode();
                                    }
                                }
                            }
                        });
                    }
                    //                    Messager.Show(msg);
                }
            });
        }
    }

    private void createSubIrDev() {
        if (mType == Device.AC && mCodeType != 1) {
            if (mOnApplianceSelectListener != null) {
                mOnApplianceSelectListener.onApplianceSelect(BlirConst.getDevType(mType), mDevName);
            }
            new SaveIrTask(getContext(), mSubBLir).execute(DBUtils.CODE_TYPE_API, DBUtils.CODE_TYPE_API, null);
        } else {
            KookongSDK.getIRDataById(mRemoteids.get(mIndex) + "", mType, new IRequestResult<IrDataList>() {

                @Override
                public void onSuccess(String msg, IrDataList result) {
                    List<IrData> irDatas = result.getIrDataList();
                    for (int i = 0; i < irDatas.size(); i++) {
                        Log.e("getIRDataById", "The rid is " + irDatas.get(i).rid);
                        final IrData irData = irDatas.get(i);
                        int size = irData.keys.size();
                        for (int j = 0; j < size; j++) {
                            IrData.IrKey irKey = irData.keys.get(j);
                            Log.e("testIRDataById", "irKey.fkey: " + irKey.fkey);
                            Log.e("testIRDataById", "irKey.pulse: " + irKey.pulse);
                            Log.e("testIRDataById", "irKey.fname: " + irKey.fname);
                            Log.e("getIRDataById", "--------------------------------------------------");
                        }

                        if (mOnApplianceSelectListener != null) {
                            IOTSubBLir subBLir = mOnApplianceSelectListener.onApplianceSelect(BlirConst.getDevType(mType), mDevName);
                            new SaveAllIrTask(getContext(), subBLir).execute(irData.keys);
                        }
                    }

                }

                @Override
                public void onFail(Integer errorCode, String msg) {
                    //按红外设备授权的客户，才会用到这两个值
                    if (errorCode == AppConst.CUSTOMER_DEVICE_REMOTE_NUM_LIMIT) {//同一个设备下载遥控器超过了50套限制
                        ThreadPoolUtils.getInstance().addTask(new Runnable() {
                            @Override
                            public void run() {
                                long kkInitId = DBUtils.getKKInitId(mRemoteids.get(mIndex));
                                if (kkInitId >= 0) {
                                    boolean result = KookongSDK.init(getContext(), SubBlirControlView.KK_APP_KEY, kkInitId + "");
                                    Log.e("KKR", "Verify result is " + result + ", KK_irDeviceId: " + kkInitId);
                                    if (result) {
                                        SubBlirControlView.KK_irDeviceId = kkInitId;
                                        createSubIrDev();
                                    }
                                }
                            }
                        });
                        msg = "下载的遥控器超过了套数限制";
                    } else if (errorCode == AppConst.CUSTOMER_DEVICE_NUM_LIMIT) {//设备总数超过了授权的额度
                        msg = "设备总数超过了授权的额度";
                        Messager.Show(msg);
                    }
                    Log.e("getIRDataById", "msg: " + msg + ", errorCode: " + errorCode);
                }
            });
        }
    }
}
